package com.ocom.srvpamh.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ocom.common.utils.*;
import com.ocom.common.vo.srvpamh.PabyUserInfoVo;
import com.ocom.common.vo.srvpamh.PabyUserVo;
import com.ocom.common.vo.srvpamh.PabyUserVo2;
import com.ocom.common.vo.srvpamh.PabyVo;
import com.ocom.redis.util.RedisUtil;
import com.ocom.srvpamh.service.PinganbaiyunService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.ParseException;
import java.util.*;

/**
 * @Description: TODO
 * @Author: 朱晖
 * @Date: 2022/12/8
 **/
@Slf4j
@Service
public class PinganbaiyunServiceImpl  implements PinganbaiyunService {

	@Resource
	private RedisUtil redisUtil;

	/**
	 * appId：B15005
	 * appKeySecret：siyBqpab7HW4R3Vq5qng3yQ7JQMZtvLM
	 */

	String appId = "B15005";
	String appKeySecret = "siyBqpab7HW4R3Vq5qng3yQ7JQMZtvLM";

	@Override
	public JsonResponse getUserInfo(String content) throws ParseException, IOException {

		String token = getAccessToken();
		if(CommonUtil.isNull(token)){
			log.info("平安白云获取token失败");
			return JsonResponse.error();
		}
		log.info("返回token 【{}】",token);

		String time  = String.valueOf(System.currentTimeMillis()/1000);
		String nonce  = RandomUtil.getRandomString(32);

		SortedMap<String,Object> sortedMap = new TreeMap<String,Object>();
		sortedMap.put("uri","person/getPersonInfo");
		sortedMap.put("devid","xak00001");
		sortedMap.put("content",content);
		sortedMap.put("time",time);
		sortedMap.put("nonce", nonce);
		sortedMap.put("appId",appId);

		String sign = createSign(sortedMap,token);

		/**
		 * {
		 *   "devid":"F0123456",
		 *   "content":"https://xcx.pinganbaiyun.cn/qrcode/?type=person&id=VdaYEnMUnOVVuxIhdYOyQZD7zLUd/L94",
		 *   "appId":"a13001",
		 *   "time":1670464843,
		 *   "nonce":"wHMiWd2bgeBV4Ww9oqhiuOcoaeBGXaMv",
		 *   "signature":"5510fe5e3d40284b79ebf1cc0f2b2092"
		 * }
		 */
		String url = "https://miot.by.gov.cn:19812/pinganCodeHttp/person/getPersonInfo";
		JSONObject jsonObject =new JSONObject();
		jsonObject.put("devid","xak00001");
		jsonObject.put("content",content);
		jsonObject.put("appId",appId);
		jsonObject.put("time",time);
		jsonObject.put("nonce",nonce);
		jsonObject.put("signature",sign);
		String  userSec= HttpUtils.doPostBodyData(url,new HashMap<>(),jsonObject);


		PabyUserInfoVo pabyVo = JSONObject.parseObject(userSec,PabyUserInfoVo.class);

		if(!pabyVo.getReturnCode().equals("00")){
			log.info("平安白云获取人员信息失败");
			if(pabyVo.getReturnCode().equals("9996") || pabyVo.getReturnCode().equals("9993")){
				 redisUtil.del("AccessToken:PABY");
			}
			return JsonResponse.error(pabyVo.getReturnMessage());
		}

		String decrypt = HutoolAesUtil.aesDecrypt(token, pabyVo.getReturnData());


		List<PabyUserVo>  list =  JSONObject.parseArray(decrypt,PabyUserVo.class);

		PabyUserVo pabyUserVo  = list.get(0);

		PabyUserVo2 pabyUserVo2 =new PabyUserVo2();
		pabyUserVo2.setName(pabyUserVo.getName());
		pabyUserVo2.setIdCard(pabyUserVo.getId_card());
		pabyUserVo2.setPhone(pabyUserVo.getMobile_phone());

		Map<String,Object> map =new HashMap<>();
		map.put("perInforData",pabyUserVo2);
		return JsonResponse.success(map);
	}


	public   String getAccessToken()  {
		try {
			Object er = redisUtil.get("AccessToken:PABY");
			if(er!=null){
				PabyVo pabyVo = JSONObject.parseObject((String)er,PabyVo.class);
				return pabyVo.getReturnData().getAccessToken();
			}
			String url = "https://miot.by.gov.cn:19812/pinganCodeHttp/token/accessToken";
			JSONObject jsonObject =new JSONObject();
			jsonObject.put("grantType","client_credentials");
			jsonObject.put("appId",appId);
			jsonObject.put("appKeySecret",appKeySecret);
			String  re= HttpUtils.doPostBodyData(url,new HashMap<>(),jsonObject);
			PabyVo pabyVo2 = JSONObject.parseObject(re,PabyVo.class);
			if(!pabyVo2.getReturnCode().equals("00")){
				log.info("平安白云token获取失败 【{}】",pabyVo2);
				return "";
			}
			redisUtil.set("AccessToken:PABY",re,5400l);
			PabyVo pabyVo = JSONObject.parseObject(re,PabyVo.class);
			return pabyVo.getReturnData().getAccessToken();
		}catch (Exception e) {
			log.info("平安白云token获取异常 【{}】",e);
			return "";
		}
	}


	public static  String createSign(SortedMap<String,Object> parameters, String key){
		StringBuffer sb = new StringBuffer();
		Set es = parameters.entrySet();//所有参与传参的参数按照accsii排序（升序）
		Iterator it = es.iterator();
		while(it.hasNext()) {
			Map.Entry entry = (Map.Entry)it.next();
			String k = (String)entry.getKey();
			Object v = entry.getValue();
			//空值不传递，不参与签名组串
			if(null != v && !"".equals(v)
					&& !"sign".equals(k) && !"key".equals(k)) {
				sb.append(k + "=" + v + "&");
			}
		}
		sb=sb.append("accessToken="+key);
		System.out.println("加密前的参数："+sb);
		//MD5加密,结果转换为大写字符
		String sign = MD5.MD5Encode(sb.toString(),"utf8").toLowerCase();
		System.out.println("加密后:"+sign);
		return sign;
	}



}
